package com.xilihui.xlh.business.manager;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;


import com.xilihui.xlh.BuildConfig;
import com.xilihui.xlh.business.requests.SignedService;
import com.xilihui.xlh.core.app.ForegroundCallbacks;
import com.xilihui.xlh.core.http.HttpManager;
import com.xilihui.xlh.core.rxbus.RxBus;
import com.xilihui.xlh.core.util.FileUtil;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.ToastUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class DownloadManager {

    /**
     * 下载图片
     */
    public static void downloadImage(final Context context, final String url) {
        
        HttpManager.getDownloadRetrofit()
                .create(SignedService.class)
                .downloadImages(url)
                .subscribeOn(Schedulers.io())
                .map(new Func1<ResponseBody, File>() {
                    @Override
                    public File call(ResponseBody responseBody) {
                        // IO线程写入文件
                        return writeFileToDisk(context, responseBody);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .map(new Func1<File, Void>() {
                    @Override
                    public Void call(final File file) {
                        // 其次把文件插入到系统图库
                        try {
                            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                                    file.getAbsolutePath(),file.getName(), null);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        // 最后通知图库更新
                        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Void>() {
                    @Override
                    public void onCompleted() {
                        ToastUtil.toastShortPositive("下载完成");
                    }

                    @Override
                    public void onError(Throwable e) {
                       ToastUtil.toastShortNegative("下载失败");
                    }

                    @Override
                    public void onNext(Void downloadCompleted) {
                        
                    }
                });
        
    }

    private static File writeFileToDisk(Context context, ResponseBody body) {

        // APK文件缓存路径
        File file = FileUtil.saveFile();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            byte[] fileReader = new byte[1024];

            inputStream = body.byteStream();
            outputStream = new FileOutputStream(file);

            while (true) {
                int read = inputStream.read(fileReader);
                if (read == -1) {
                    break;
                }
                outputStream.write(fileReader, 0, read);
            }
            outputStream.flush();
            return file;

        } catch (IOException e) {
            return file;
        } finally {

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
